package com.zzyl.job;

import cn.hutool.json.JSONUtil;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.print.attribute.standard.PresentationDirection;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Author 小王要变胖
 * @Date 2025/2/16 17:20
 * @注释
 */
@Component
public class AlertRuleCronJob {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private AlertRuleService alertRuleService;

    @Scheduled(cron = "0,10,20,30,40,50 * * * * ? ")
    public void deviceDataAlertFilter(){
        // 查询所有规则
        List<AlertRule> alertRuleAll = alertRuleMapper.selectAllRule(null,null,null);
        if(ObjectUtil.isEmpty(alertRuleAll)){
            return;
        }

        // 查询所有设备的上报数据,没有数据直接返回
        List<Object> values = redisTemplate.opsForHash().values("deviceData");
        if(ObjectUtil.isEmpty(values)){
            return;
        }

        // 数据不为空，封装数据
        List<DeviceDataVo> allDeviceDataVoList = new ArrayList();
        values.forEach(v->{
            List<DeviceDataVo> deviceDataVoList = JSONUtil.toList(v.toString(), DeviceDataVo.class);
            allDeviceDataVoList.addAll(deviceDataVoList);
        });

        // 对每一条数据进行上报校验
        allDeviceDataVoList.forEach(item ->{
            alertRuleService.alertFilter(item);
        });

    }

}
